#include "tscreen.h"
#include "ui_tscreen.h"
#include <QScrollArea>  // 滚动条
#include <QDateTime>
#include <QTimer>
#include <QMessageBox>
#include <QDir>   // 文件路径
#include <QClipboard> // 剪切板
#include <QColor>


#include "common.h"

TScreen::TScreen(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TScreen)
{
    ui->setupUi(this);


    QRect rcLabel = ui->label->geometry();
    // 初始化指针
    picOrg = NULL;
    mScreen = NULL;
    picChg = NULL;
    isOperation = false;
    // 将滚动条加入标签，后续可以对超过标签大小的图片进行滚动查看
    QScrollArea *pSA = new QScrollArea(this);
    // 将标签填充到滚动条
    pSA->setWidget(ui->label);
    // 滚动条大小设置和标签大小一致
    pSA->setGeometry(rcLabel);


    // 定时器进行实时时间刷新
    mTimer = new QTimer(this);
    mTimer->setSingleShot(false); // 非单次触发即循环触发
    mTimer->setInterval(1 * 1000); // 间隔为1s
    connect(mTimer,SIGNAL(timeout()),this,SLOT(updateRealTime()));
    mTimer->start();

    capScreen = new CapScreen();
    connect(capScreen,&CapScreen::signalShotPixmap,this,&TScreen::slotShotPixmap);
}

TScreen::~TScreen()
{
    claer();
    delete ui;
}


void TScreen::claer(){
    if (picOrg != NULL){
        delete picOrg;
        picOrg = NULL;
    }

    if (picChg != NULL){
        delete picChg;
        picChg = NULL;
    }

    if (mScreen != NULL){
        delete mScreen;
        mScreen = NULL;
    }


    if (mTimer != NULL){
        delete mTimer;
        mTimer = NULL;
    }

}

QRect TScreen::getRect(QPoint start,QPoint end){
    return  QRect(start.x(),start.y(),end.x(),end.y());
}

void TScreen::slotShotPixmap(QPixmap qp){
    ui->label->clear();

    if (!qp.isNull()){
        if (picOrg == NULL) {
            picOrg = new QPixmap;
        }
        *picOrg = qp.scaled(ui->label->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        ui->label->setPixmap(*picOrg);
        copyImage2Clipboard(*picOrg);
    }
    this->show();
}



void TScreen::updateRealTime(){
    QDateTime dt = QDateTime::currentDateTime(); // 获取当前时间
    QString strTime = dt.toString("yyyy年-MM月-dd日 HH:mm:ss");

    if (picOrg == NULL){
        ui->label->clear();
//        ui->label->setTextFormat(Qt::PlainText);
//        ui->label->setStyleSheet("color: black;font-size: 70px");
//        ui->label->setAlignment(Qt::AlignCenter);
//        ui->label->setText("当前时间为:" + strTime + "\n" );

//        ui->label->setStyleSheet("color: red;font-size: 50px;");

        QString htmlContent = QString("<div style='text-align: center; font-size: 70px; color: blue;'>%1</div>")
                                   .arg(strTime);

        ui->label->setText(htmlContent +
                           "<div style='position: relative; height: 100%;'>"
                           "<div style='position: absolute; bottom: 0; left: 0;'>"
                           "使用方法：<br>"
                           "<br>截取全屏为截取整个屏幕，无需额外操作; <br>"
                           "<br>选择截图为截取鼠标所选区域，选择完成后按键1确定，esc重新选择，2退出选择截图界面;使用ctrl+shift+A 可以实现全屏截取;<br>"
                           "<br>取消为取消截图，清空图片显示 <br>"
                           "<br>保存为将截取的图片进行保存 <br>"
                           "</div></div>");
    }
}


void TScreen::on_pushButtonCap_clicked()
{
    // 防止重复点击报错 -- 点击截取全屏后是可以再进行点击重新截取的，不需要额外操作
    if (isOperation && picOrg == NULL) {
        QMessageBox::information(this,"提醒","正在进行其他操作");
        return ;
    }else{
        isOperation = true;
    }


    // 每次截图前初始化指针
    if (picOrg != NULL){
        picOrg = NULL;
    }else{
        picOrg = new QPixmap();
    }

    if (picChg != NULL){
        picChg = NULL;
    }else{
        picChg = new QPixmap();
    }

    // 隐藏截取框
    this->hide();
    QApplication::processEvents();
    // 这里加延时因为不加会导致隐藏时间太短而显示
    QTimer::singleShot(500, this, [this](){
        mScreen = QGuiApplication::primaryScreen();
        // QApplication::desktop()->winId(); // 获取当前屏幕，有问题暂时屏蔽，使用固定0
        *picOrg =  mScreen->grabWindow(0);
        picChg = picOrg;
        ui->label->setPixmap( *picChg   /*(*picChg).scaled(800, 600, Qt::KeepAspectRatio, Qt::SmoothTransformation)*/);
        ui->label->setGeometry( picChg->rect() /* (*picChg).scaled(800, 600, Qt::KeepAspectRatio, Qt::SmoothTransformation).rect()*/);

        this->show(); // 显示截取框

        // 将图片复制到剪切板，可以直接粘贴发送
        copyImage2Clipboard(*picOrg);
        isOperation = false;
    });
}


void TScreen::on_pushButtonSave_clicked()
{
    if (picOrg == NULL){
        return;
    }

    QString path = "../TScreen/imgSave/";
    QString savePath = path;
    if (! QDir(path).exists()){
        QMessageBox::critical(this,"错误提示","路径不存在!!!");
        return;
    }

    // 保存图片
    const char * imgFormat = getImgFormat(PNG); // todo: 这里固定了图片格式，按道理是应该选择保存为何种格式
    savePath += QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss") + "." + imgFormat; // 20241223_11_11_11.png
    if (! picOrg->save(savePath,imgFormat)){
        QMessageBox::critical(this,"错误提示","保存错误!!!");
    }else{
        QMessageBox::information(this,"成功提示","保存成功!!!");
        isOperation = false;
    }
}


void TScreen::on_pushButtonCancel_clicked()
{
    // 取消则清空显示并提示已取消截取
    if (picOrg != NULL) {
        ui->label->clear();
        isOperation = false;
        picOrg = NULL;
        QMessageBox::information(this,"取消截图","你取消了截图操作");
    }
}


void TScreen::on_pushButtonCapRange_clicked()
{
    if (!isOperation){
        isOperation = true;
        this->hide();

        QTimer::singleShot(200,Qt::PreciseTimer,this,[this]()
        {
            capScreen->show();
        });
    }

    isOperation = false;
}

/*未实现槽函数*/
void TScreen::RecvPlayError(QImageReader::ImageReaderError  error){} // 接收出错的信号
void TScreen::RecvFrameNumber(int freameNumber){}  // 接收播放时帧号的变化
